<?
global $AppUI, $obj, $users;

if (!defined('DP_BASE_DIR')) {
	echo 'You should not access this file directly.';
	exit();
}

$root = defined('DP_PROJECT_DIR') ? DP_PROJECT_DIR : DP_BASE_DIR.'/files/projects';

// Direct access
if (!isset($obj)) {
	if (!isset($_REQUEST['task'])) {
		if (!isset($AppUI)) {
			echo 'You should not access this file directly.';
			exit();
		}
		else {
			$AppUI->setMsg('Missing task information', UI_MSG_WARNING);
			$AppUI->redirect();
		}
	}
	$obj = new CTask();
	$obj->load($_REQUEST['task']);
}

$p = new CProject($obj->task_project);

$q = new DBQuery();
$q->addTable('user_tasks');
$q->addQuery('user_id');
$q->addWhere('task_id = '.$obj->task_id);
$users = arrayMerge(array($obj->task_creator => ''), $q->loadHashList());

$canUpload = ($AppUI->user_id == $p->getManager()) || in_array($AppUI->user_id, array_keys($users));
$cmd = isset($_REQUEST['cmd']) ? $_REQUEST['cmd'] : 'list';

if ($cmd != 'get' && $cmd != 'list' && !$canUpload) {
	$AppUI->setMsg('You dont have permission to '.$cmd.' file', UI_MSG_ERROR);
	$AppUI->redirect('&m=tasks&a=view&task_id='.$obj->task_id);
	exit();
}

switch ($cmd) {
	case 'get':
		getfile();
		break;
	case 'put':
		putfile();
		break;
	case 'update':
		updatefile();
		break;
	case 'delete':
		delfile();
		break;
	default:
		break;
}

$task_folder = $root . '/' . $obj->task_project . '/' . $obj->task_id;
if (!is_dir($task_folder)) {
	if (version_compare(phpversion(), '5.0') < 0) {
		$project_folder = $root . '/' . $obj->task_project;
		if (!is_dir($root))
			mkdir($root, 0700);
		if (!is_dir($project_folder))
			mkdir($project_folder, 0700);
		if (!is_dir($task_folder))
			mkdir($task_folder);
	}
	else {
		mkdir($task_folder, 0700, true);
	}
}

$q->addTable('files');
$q->addWhere('file_project = '.$obj->task_project);
$q->addWhere('file_task = '.$obj->task_id);
$q->addOrder('file_name');
$data = $q->loadHashList('file_real_filename');
$total = count($data);

if ($canUpload) {
?>
<!-- Begin upload file dialog -->
<div id="idNewFile" class="popup" style="visibility: hidden; padding: 8px">
<form name="uploadFrm" action="?m=tasks&a=file&suppressHeaders=1" enctype="multipart/form-data" method="post">
<input type="hidden" name="cmd" value="put">
<input type="hidden" name="project" value="<?=$obj->task_project?>">
<input type="hidden" name="task" value="<?=$obj->task_id?>">
<input type="hidden" name="file" value="">
<table border="0" cellpadding="4" cellspacing="2">
	<tr>
		<td align="right">File</td>
		<td>
			<span id="idFileName"></span>
			<input id="idFile" type="file" name="taskfile" class="text" size="45"/>
		</td>
	</tr>
	<tr>
		<td align="right">Version</td>
		<td><?=createSpinBox('file_version', '1.0', 0, 10, '', 0.1)?></td>
	</tr>
	<tr>
		<td valign="top">Description</td>
		<td><textarea id="idFileDesc" name="file_description" style="width: 300px; height: 100px"></textarea></td>
	</tr>
	<tr>
		<td colspan="2" align="center">
			<input type="submit" value="Save"/>&nbsp;
			<input type="button" value="Cancel" onclick="Dialog('idNewFile').hide()"/>
		</td>
	</tr>
</table>
</form>
</div>
<!-- End upload file dialog -->
<? } ?>

<table border="0" cellpadding="7" cellspacing="0" class="infopanel" width="100%">
<tr>
	<td>
	<? if ($canUpload) { ?>
		<input type="button" value="New file" onclick="doNewFile()"/>
	<? } ?>
	</td>
</tr>
</table>
<table id="idFileList" border="0" cellpadding="0" cellspacing="0" class="list" width="100%">
<tr>
	<th width="14px">&nbsp;</th>
	<th nowrap="nowrap">File name</th>
	<th width="30px">Ver.</th>
	<th width="45px">Owner</th>
	<th width="45px">Size</th>
	<th width="100px">Date</th>
	<th width="100%">Description</th>
	<th width="14px" class="last">&nbsp;</th>
</tr>
<?
if ($total == 0) {
	showEmptyRow(8, 'second');
}
else
foreach ($data as $f => $d)
if (file_exists($task_folder . '/' . $f)) {
?>
<tr id="<?=$f?>" class="second">
	<td align="center">
	<? if ($canUpload) { ?>
		<img src="images/edit_log.gif" onclick="doEditFile(this)"/>
	<? } else { ?>
		<img src="images/log.gif"/>
	<? } ?>
	</td>
	<td nowrap="nowrap" onclick="doViewFile(this)"><?=$d['file_name']?></td>
	<td><?=sprintf('%.2f', $d['file_version'])?></td>
	<td nowrap="nowrap"><?=dPgetUsernameFromID($d['file_owner'])?></td>
	<td onclick="doViewFile(this)"><?=$d['file_size']?></td>
	<td nowrap="nowrap" onclick="doViewFile(this)"><?=substr($d['file_date'], 0, strrpos($d['file_date'], ':'))?></td>
	<td onclick="doViewFile(this)"><?=$d['file_description']?></td>
	<td align="center">
	<? if ($canUpload) { ?>
		<img src="images/delete_log.gif" onclick="doDeleteFile(this)"/>
	<? } else { ?>
		<img src="images/nodel_log.gif"/>
	<? } ?>
	</td>
</tr>
<? } ?>
</table>
<? if ($canUpload) { ?>
<script>
var frm = document.uploadFrm;

function doNewFile()
{
	frm.cmd.value = 'put';

	Control('idFile').show();
	Control('idFile').disabled = false;
	$('idFileName').innerHTML = '';
	$('idFile_version').value = '1.0';
	$('idFileDesc').value = '';
	Dialog('idNewFile').show();
}

function doEditFile(ctrl)
{
	var r = ctrl.parentNode.parentNode;
	var fn = r.id;

	frm.cmd.value = 'update';
	frm.file.value = fn;

	Control('idFile').hide();
	Control('idFile').disabled = true;
	$('idFileName').innerHTML = r.cells[1].innerHTML;
	$('idFile_version').value = parseFloat(r.cells[2].innerHTML);
	$('idFileDesc').value = r.cells[6].innerHTML;
	Dialog('idNewFile').show();
}

function doDeleteFile(ctrl)
{
	var fn = ctrl.parentNode.parentNode.id;
	var rn =  ctrl.parentNode.parentNode.cells[1].innerHTML;

	if (!confirm('Are you sure you want to delete file:\n'+rn+' ?'))
		return;

	go('index.php?m=tasks&a=file&suppressHeaders=1&cmd=delete&file='+fn+
		'&project=<?=$obj->task_project?>&task=<?=$obj->task_id?>');
}
</script>
<? } ?>

<script>
function doViewFile(cell)
{
	var fn = cell.parentNode.id;
	go('index.php?m=tasks&a=file&suppressHeaders=1&cmd=get&file='+fn+
		'&project=<?=$obj->task_project?>&task=<?=$obj->task_id?>', 'sdp_fileviewer');
}

Table('idFileList').setNormalHover(1);
</script>

<?
function getfile()
{
	global $root;

	$q = new DBQuery();
	$q->addTable('files');
	$q->addWhere('file_real_filename = "'.$_GET['file'].'"');
	$q->addWhere('file_project = '.$_GET['project']);
	$q->addWhere('file_task = '.$_GET['task']);
	$q->addOrder('file_name');
	$data = $q->loadHash();

	$file = $root.'/'.$_GET['project'].'/'.$_GET['task'].'/'.$_GET['file'];
	if ($data['file_type'] == '')
		$data['file_type'] = 'application/octet-stream';

	header( 'MIME-Version: 1.0' );
	header( 'Pragma: ' );
	header( 'Cache-Control: public' );
	header( 'Content-length: ' . $data['file_size'] );
	header( 'Content-type: ' . $data['file_type'] );
	header( 'Content-transfer-encoding: 8bit' );
	header( 'Content-disposition: inline; filename="' . $data['file_name'] . '"' );

	$fd = fopen($file, 'rb');
	if ($fd) {
		while ( !feof($fd) ) {
			print fread($fd, 8192);
		}
		fclose($fd);
	}
}

function putfile()
{
	global $AppUI, $root;

	$upload = $_FILES['taskfile'];
	$path = $root.'/'.$_POST['project'].'/'.$_POST['task'].'/';
	$file_real_filename = md5($path . $upload['name']);
	$file = $path . $file_real_filename;
	move_uploaded_file($upload['tmp_name'], $file);

	$fields = array(
		'file_real_filename',
		'file_project',
		'file_task',
		'file_name',
		'file_size',
		'file_type',
		'file_date',
		'file_description',
		'file_owner',
		'file_version'
	);
	$values = array(
		$file_real_filename,
		$_POST['project'],
		$_POST['task'],
		$upload['name'],
		$upload['size'],
		$upload['type'],
		date('Y-m-d H:i:s', filectime($file)),
		$_POST['file_description'],
		$AppUI->user_id,
		$_POST['file_version']
	);

	$q = new DBQuery();
	$q->addTable('files');
	$q->addInsert($fields, $values, true);
	$q->exec();

	$AppUI->redirect('&m=tasks&a=view&task_id='.$_POST['task']);
}

function delfile()
{
	global $AppUI, $root;

	$q = new DBQuery();
	$q->setDelete('files');
	$q->addWhere('file_project = '.$_REQUEST['project']);
	$q->addWhere('file_task = '.$_REQUEST['task']);
	$q->addWhere('file_real_filename = "'.$_REQUEST['file'].'"');
	$q->exec();

	unlink($root.'/'.$_REQUEST['project'].'/'.$_REQUEST['task'].'/'.$_REQUEST['file']);

	$AppUI->redirect('&m=tasks&a=view&task_id='.$_GET['task']);
}

function updatefile()
{
	global $AppUI, $root;

	$fields = array(
		'file_description',
		'file_version'
	);
	$values = array(
		$_POST['file_description'],
		$_POST['file_version']
	);

	$q = new DBQuery();
	$q->addTable('files');
	$q->addUpdate($fields, $values, true);
	$q->addWhere('file_project = '.$_REQUEST['project']);
	$q->addWhere('file_task = '.$_REQUEST['task']);
	$q->addWhere('file_real_filename = "'.$_REQUEST['file'].'"');
	$q->exec();

	$AppUI->redirect('&m=tasks&a=view&task_id='.$_REQUEST['task']);
}
?>
